﻿using Google.Protobuf.Collections;
using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Qdrant.Client.Grpc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace QdrantConnector
{
    [Icon("pack://application:,,,/QdrantConnector;component/Resources/Icon.png")]
    [Designer("QdrantConnector.Designer.QdrantConnectorServerCommandDesigner, QdrantConnector")]
    [Category("Qdrant向量数据库")]
    [OrderWeight(200)]
    internal class AddToCollection : BaseQdrantOp
    {
        [FormulaProperty]
        [OrderWeight(100)]
        [DisplayName("导入的向量数组（JSON）")]
        [Description("需要插入集合的向量数组，形如[{\"id\":1,\"embedding\":[0.112,0.9871,...],\"payload\":{\"key\":\"a1\",\"key2\":\"b1\"}}},{\"id\":2,\"embedding\":[0.311,0.561,...]},\"payload\":{\"key\":\"a1\",\"key2\":\"b1\"}]")]
        public object ArrayFormula { get; set; }

        public override async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var listJSON = (await dataContext.EvaluateFormulaAsync(this.ArrayFormula))?.ToString() ?? "[]";

            var vectors = Converters.ToPoint(listJSON);

            var client = await getQrantClient(dataContext);

            var collectionName = await getCollectionName(dataContext);

            if (vectors.Count > 0)
            {
                dataContext.Log.AppendLine($"开始向Qdrant集合【{collectionName}】中添加向量...");
                var tick = DateTime.Now;

                await client.UpsertAsync( collectionName, vectors);

                dataContext.Log.AppendLine($"向量添加到集合【{collectionName}】成功，共添加{vectors.Count}个向量，耗时：{(DateTime.Now - tick).TotalMilliseconds}ms");

            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "Qdrant导入向量";
        }

        
    }
}
